package day20180528;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class DES3Util {
    public static void main(String[] args) throws Exception{
        byte[] keys=initKey();
        byte[] miwen= encrpt("我爱你".getBytes(),keys);
        byte[] mingwen=decrpt(miwen,keys);
        System.out.println(new String(mingwen));

    }

    /**
     * 获得秘钥
     * @return
     */
    public static byte[] initKey(){
        try {
            KeyGenerator keyGenerator=KeyGenerator.getInstance("DESede");
            keyGenerator.init(168); // 密钥长度 112 168
            SecretKey secretKey=keyGenerator.generateKey();
            return secretKey.getEncoded();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * encrpt :解密
     * cipher: 用密码书写
     * @param data
     * @param key
     * @return
     * @throws NoSuchPaddingException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public static byte[] encrpt(byte[] data,byte[] key) throws Exception {
        Cipher cipher=Cipher.getInstance("DESede");
        cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(key,"DESede"));
        return cipher.doFinal(data);
    }

    /**
     * encrpt :解密
     * cipher: 用密码书写
     * @param data
     * @param key
     * @return
     * @throws NoSuchPaddingException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public static byte[] decrpt(byte[] data,byte[] key) throws Exception {
        Cipher cipher=Cipher.getInstance("DESede");
        cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(key,"DESede"));
        return cipher.doFinal(data);
    }
}
